/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package au.edu.swin.swinvehicle.manager;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Administrator
 */
public class AuthenticationManagerJSFManagedBean {

    public static final String LOGIN = "login";
    public static final String HOME = "home";
    @EJB
    private ManagerManagerRemote managerManagerRemote;
    private ManagerDetailedTO manager;
    private String username;
    private String password;

    /** Creates a new instance of AuthenticationManagerJSFManagedBean */
    public AuthenticationManagerJSFManagedBean() {
        this.manager = new ManagerDetailedTO();
    }

    public String login() {
        try {
            Long managerId = this.managerManagerRemote.authenticate(username, password);

            if (managerId != null) {
                this.manager = this.managerManagerRemote.getManager(managerId);
                return HOME;
            } else {
                FacesContext context = FacesContext.getCurrentInstance();
                FacesMessage message = new FacesMessage("Invalid Username and/or Password");
                context.addMessage("authenticationForm", message);
                return LOGIN;
            }
        } catch (ManagerManagerException ex) {
            Logger.getLogger(AuthenticationManagerJSFManagedBean.class.getName()).log(Level.SEVERE, null, ex);
            FacesContext context = FacesContext.getCurrentInstance();
            FacesMessage message = new FacesMessage("An error occured, cannot authenticate user");
            context.addMessage("authenticationForm", message);
            return LOGIN;
        }
    }

    public String logout() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession httpSession = (HttpSession) facesContext.getExternalContext().getSession(false);
        httpSession.invalidate();

        return LOGIN;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public ManagerDetailedTO getManager() {
        return manager;
    }

    public void setManager(ManagerDetailedTO manager) {
        this.manager = manager;
    }
}
